package top101K.binarySearch;

/**
 * @Author quan
 * @Description 二分查找：无重复数字的升序数组的二分查找
 * [-1,0,3,4,6,10,13,14],13——>6
 * @Date 2023/8/2 22:26
 */
public class Demo17_BinarySearch {
    /**
     * 二分查找：中间值与目标值对比，不断缩小区间。注意一般不确定此时的循环都使用while方式，而不是for循环
     * @param nums 排序数组
     * @param target  目标值
     * @return 返回数组元素下标
     */
    public static int search (int[] nums, int target) {
        //找出中间索引下标
        int left = 0;
        int right = nums.length-1;
        while (left <= right){
            int mid = (right+left)/2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] < target){
                left = mid+1;
            }else{
                right = mid-1;
            }
        }
        return -1;
    }

    /**
     * 递归的二分法查找
     * @param nums
     * @param target
     * @return
     */
    public static int search1 (int[] nums, int target) {
        return search1(nums, 0, nums.length - 1, target);
    }
    private static int search1(int[] nums, int left, int right, int target) {
        //base case
        if (left > right) {
            return -1;
        }
        //递归
        int mid = (left+right)/2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] > target) {
            return search1(nums, left, mid - 1, target);
        } else {
            return search1(nums, mid + 1, right, target);
        }
    }
}
